	<?php 
		function getFooter($tables){
	?>
		



		<script>
			//window.$ = jQuery;
		</script>

	<?php


			$select = array();
			//$ko_path =  plugins_url( '/knockout-3.1.0.js', __FILE__ ) ;
			$ko_path =  plugins_url( '/knockout-3.1.0.debug.js', __FILE__ ) ;
			$ko_map =  plugins_url( '/knockout.mapping-latest.js', __FILE__ ) ;
			$alertify = plugins_url('/alertify/alertify.js',__FILE__);
			
			//$jq_acmpl =  plugins_url( '/jquery.ui.autocomplete.js', __FILE__ ) ;
			
			$current_user = wp_get_current_user(); 
			if($current_user->ID == 0){
				return '';
			}
			
			foreach ($tables as  $table_name) {
				$table = new TableORM($table_name);
				$res = $table->findAllForSelect();
				$res["value"] = "";
				$select[$table_name] = $res;
				//echo " $table_name - ";
			}

	?>

	<!--form action="<?php echo admin_url( 'admin-post.php' ); ?>"-->

	

	
	<?php 
	//DEBUG
	if(false){
	?>
		<input type="text" id= 'pickd'>	 <hr>
		<input type="text" data-bind="datepicker:dataP">	 <hr>


		<form action="/blog/wp-content/plugins/timetable/includes/payreq.php" method="POST">
			<input type="text" placeholder="amount" name="amount" value="100" ><br>
			<input type="text" placeholder="userid" name="userid" value="000000016_20140726115526_g70EwHr1wOfMe7HnBjZpocjh5W39lF1kf8mjbeS" ><br>
			<input type="text" placeholder="paymentid" name="paymentid" value="14758" ><br>
			<input type="text" placeholder="key" name="key" value="" ><br>
			<input type="text" placeholder="paymode" name="paymode" value="1" ><br>
			<input type="text" placeholder="userid_extra" name="userid_extra" value="" ><br>
			<input type="text" placeholder="orderid" name="orderid" value="" ><br>
			<input type="text" placeholder="test" name="test" value="" ><br>
			<input type="submit">
		</form>

	<?php } //DEBUG  ?>

	<script src="<?php echo $alertify; ?>"></script>

	<!--script src="http://yandex.st/jquery/2.1.0/jquery.min.js"></script-->
	<script src="http://yandex.st/lodash/2.4.1/lodash.min.js"></script>

	<script src="<?php echo $ko_path; ?>"></script>

	<!--script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js"></script-->



	<script>

		var adminurl = "<?php  echo admin_url('admin-ajax.php'); ?>";
		var ajaxurl = ajaxurl || adminurl;
		var selects = <?php echo json_encode($select);?>
	</script>

	<script>



		var EventModelForViewTable = {

					clickCell:function(e){
						var edit = e.state.edit();
						var items = e.parent.model.body();
						items = _.filter(items, function(item){
							return !item.state.new_item();
						});											
						e.state.edit(  !edit );
						e.parent.model.body(items);
					},
					clickCellSave:function(e){
						_.forOwn(e.selects, function(data_1, key_1){
	    						_.forOwn(data_1.value, function(data_2, key_2){
	    							if(e.items()[key_2] != undefined){	
										if(key_2 !== 'field'){
											var key = key_2;
										    var item = e.items()[key_2]();
											var val = 	data_2;
											e.items()[key_2](data_2);
										}
									}											
	    						});
						});


						var items = {};
						_.forOwn(e.items(), function(val,key){
							items[key] = val();
						});

						var method = "update";
						var reload = false;

						var dataS = {
								table_name: e.table_name,
								table_data: items,
								table_method: method
						};

						if( e.state.new_item() ){

							method = "insert"
							dataS.table_method = method;
							
							if(e.table_name === 'clientcourse'){
								if(e.parent.clientcourse){
									e.parent.root.choiceDiv.link = dataS;
									e.parent.getUsers(e.items().client_name(), e);
								}
							}
							reload = true;
						}

						//if( method !== "insert"){
						//if( e.table_name !== 'clientcourse' ){
						if( true ){
							

							//console.log(dataS);
							
							//console.log(ajaxurl + "?action=test_ajax");
							jQuery.ajax({
								type:'POST',
								url:ajaxurl + "?action=test_ajax",
								data:dataS	
							})
							.done(function(resp){
								e.state.edit(false);
								e.state.new_item(false);
								//console.log(resp);
								if(reload){
									if(e.table_name !== 'clientcourse' && method === "insert"){
									}else{
										window.location.reload();
									}
								}	
							});
						}
					},
					clickCellDelete:function(e){
						alertify.confirm('Удалить запись?', function(ae){
							if(ae){
								var items = {};
								_.forOwn(e.items(), function(val,key){
									items[key] = val();
								});

								var dataS = {
									table_name: e.table_name,
									table_data: items,
									table_method:'delete'
								};

								jQuery.ajax({
									type:'POST',
									url:ajaxurl + "?action=test_ajax",
									data:dataS	
								})
								.done(function(resp){
									//console.log(resp);
									
									var deleted_num = e.row_num();
									var items = _.reject( e.parent.model.body(), function(item){
										var deln = deleted_num;
										var it = item.row_num();
										return deleted_num === item.row_num();
									} );
									e.parent.model.body(items);
									//console.log(e);						
									window.location.reload();
								});
							}
						});
						
					},
					clickRow:function(e){
						//console.log(e);
					},
					dblClickCell:function(){},
					dblClickRow:function(){},
					selected:function(e){

					}
				}

		function ViewsTableModel(data,  parent, selects){
			var self = this;
			self.model = {};
			self.model.table_name = data.table_name;

			self.root = parent;

			self.sort_state = {
				field:'',
				order_direction:1
			}

			self.clientcourse = self.model.table_name === 'clientcourse';

			
			self.model.users = ko.observableArray();
			self.getUsers = function(client_name, e){
				var dataS = {
							table_name: 'users',
							table_data: {
								client_name: client_name
							},
							table_method:'searchUsers'
						};

						jQuery.ajax({
							type:'POST',
							url:ajaxurl + "?action=test_ajax",
							data:dataS	
						})
						.done(function(resp){
					
							var pos = resp.indexOf('[{');
							resp = resp.slice(pos);
							var tail = resp.slice(resp.length -2, resp.length );
							if(tail === "]0") {
								resp =  resp.slice(0,-1);
							}
							
							resp = JSON.parse(resp);

							//console.log(resp);
							//parent.choiceDiv.link = self;

							var arr_resp = _.map(resp, function(item){
								item.parent = e;
								item.click = function(){
									/*
										alertify.confirm(
											'Выбран пользователь ' + item.client_name + "! Вы уверены?", 
											function(ev){*/
									//	if(ev){

										alertify.confirm('Выбран пользователь ' + item.client_name + "! Вы уверены?", function(ev){
											if(ev){


											e.items().client_contact(item.client_contact);
											e.items().client_name(item.client_name);
											e.items().client_id(item.client_id);

											var items = {};
											_.forOwn(e.items(), function(val,key){
												items[key] = val();
											});

											var dataS = {
												table_name: e.table_name,
												table_data: items,
												table_method: "insert"
											};

													
											jQuery.ajax({
												type:'POST',
												url:ajaxurl + "?action=test_ajax",
												data:dataS	
											})
											.done(function(resp){
												window.location.reload();
											});	
										}
									});
			
								}
								return item;
							});
							parent.clientSearchResults(arr_resp);
							//console.log(parent.clientSearchResults());
							$('#clientCourseViewUsers').show();						
						});
			}

			self.model.head = data.head;
			self.model.structure = data.structure;
			self.model.body = ko.observableArray();

			self.viewport = ko.observableArray();
			self.viewportSetting = ko.observable({
				curPage: ko.observable(1),
				recordOnPage: ko.observable(5),
				pageCount: ko.observable( 0) 
			});


			self.getPageByIdx = function(pageIndex){
				if(pageIndex === undefined){
					pageIndex = self.viewportSetting().curPage() - 1
				}else{
					self.viewportSetting().curPage(pageIndex);
					pageIndex = pageIndex - 1;
				}
				var begIdx = pageIndex*self.viewportSetting().recordOnPage();
				var endIdx = begIdx + self.viewportSetting().recordOnPage();
				var arr = self.model.body().slice(begIdx, endIdx);
				self.viewport(arr);

			}

			self.clickForward = function(){
				var curPage = self.viewportSetting().curPage();
				var pageCount = self.viewportSetting().pageCount();
				var recordOnPage = self.viewportSetting().recordOnPage();

				if(curPage < pageCount){
					self.getPageByIdx(curPage + 1);
				}

			}
			self.clickBackward = function(){
				var curPage = self.viewportSetting().curPage();
				var pageCount = self.viewportSetting().pageCount();
				var recordOnPage = self.viewportSetting().recordOnPage();

				if(curPage > 1){
					self.getPageByIdx(curPage - 1);
				}
			}

			self.enumerate = function(arr){
				var count = 1;
				var res_arr = _.map( arr, function(it){
					var item ={};
					item.parent = self;
					item.root = self.root;
					item.table_name = data.table_name;


					item.items = {};
					_.forOwn(it,function(val,key){
						item.items[key] = ko.observable(val);	
					});

					if( item.table_name === 'clientcourse' ){
						item.items['needpay_visible'] = ko.observable( item.items.needpay() >= 1 ? true: false );
					}	else {
						item.items['needpay_visible'] = ko.observable(undefined);
					}				

					item.items = ko.observable(item.items);

					item.row_num = ko.observable(count);
					item.events = {};
					_.extend(item.events,EventModelForViewTable);
					item.events.pay = function(e, e1){
						var dataS={
							table_name: "clientcourse",
							table_data: {
								clientcourse_id : it.idclientcourse
							},
							table_method: "payment"
						}
						console.log(e);
						jQuery.ajax({
							type:'POST',
							url:ajaxurl + "?action=test_ajax",
							data:dataS,
							dataType:'html'		
						})
						.done(function(resp){
							console.log( resp );
							resp = resp.slice(0,-1);
							jQuery('#paymentDivModal').html(resp);
							jQuery('#paymentDivModalbg').show();
						});
					}
					
					item.state = {
						edit:ko.observable(false),
						visible:ko.observable(true),
						new_item:ko.observable(false)
					};


					item.selects = {};

					var sel = _.clone(selects, true );

					_.extend(item.selects, sel);

					_.forOwn(item.selects, function(data_1, key_1){

						var idkey = data_1.id;
						var tobe = item.items()[idkey] !== undefined;
						if(tobe){
							var idval = item.items()[idkey]();
							var val = 0;
							for (var i = 0; i < item.selects[key_1].values.length; i++) {
								var it = item.selects[key_1].values[i];
								if(it[idkey] === idval){
									val = i;
								}
							};							
							
							item.selects[key_1].value = item.selects[key_1].values[val];
						}


					});


					count++;
					return item;
				});
				
				var divided = res_arr.length / self.viewportSetting().recordOnPage();
				var mdivided = Math.floor(divided);

				var pc =  (mdivided === divided ? mdivided : mdivided + 1) ;
				self.viewportSetting().pageCount(pc);
				self.model.body( res_arr );
				//self.viewport(res_arr);
				self.getPageByIdx();
				//console.log(self.viewportSetting());
			}
			self.enumerate( data.body ) ;


			self.newIndexes = [];

		

			self.clickNew = function(){
					var count = self.model.body().length + 1; 
					var prev = self.model.body()[0];
					var item ={};
					item.parent = self;
					item.table_name = self.model.table_name;
					item.items = {};
					_.forOwn(self.model.structure,function(val,key){
						item.items[key] = ko.observable(val);	
					});								
					item.items = ko.observable(item.items);

					item.row_num = ko.observable(count);
					item.events = {};
					_.extend(item.events,EventModelForViewTable);
					item.state = {
						edit:ko.observable(true),
						visible:ko.observable(true),
						new_item:ko.observable(true)
					};
					item.selects = {};
					_.extend(item.selects, selects);
					item.value = ko.observable('');
					self.newIndexes.push(count);				
					self.model.body.unshift(item);
					self.viewport.unshift(item);
			}

			self.sortBody = function( e, element ){

				var sort_name = $(element.target).attr('name');
				if(this.parent.sort_state.field === sort_name){
					this.parent.sort_state.order_direction = -1 * this.parent.sort_state.order_direction; 
				}else{
					this.parent.sort_state.field = sort_name;
					this.parent.sort_state.order_direction = 1;
				}

				var body_arr = this.parent.model.body();
				body_arr = _.sortBy(body_arr, function(a){

						var val = a.items()[sort_name]();
						if(parseInt(val) == val){
							val = parseInt(val);
						}

						return val;
				});
				if(this.parent.sort_state.order_direction === -1){
					body_arr = body_arr.reverse();	
				}
				
				
				this.parent.model.body(body_arr);
				this.parent.getPageByIdx();
			}		

			self.sort = function( e, element ){
				var sort_name = $(element.target).attr('name');
				if(self.sort_state.field === sort_name){
					self.sort_state.order_direction = -1 * self.sort_state.order_direction; 
				}else{
					self.sort_state.field = sort_name;
					self.sort_state.order_direction = 1;
				}

				var body_arr = self.model.body();
				body_arr = _.sortBy(body_arr, function(a){

						var val = a.items()[sort_name]();
						if(parseInt(val) == val){
							val = parseInt(val);
						}

						return val;
				});
				if(self.sort_state.order_direction === -1){
					body_arr = body_arr.reverse();	
				}
				
				
				self.model.body(body_arr);
				self.getPageByIdx();
			}		

		}


		function formatNumber(num, count, sym)
		{
			var sym = sym || '0';
			var count = count || num.toString().length;
			var format_str = '';
			for (i = 0; i < (count - num.toString().length); i++){
				format_str += sym; 
			}
			return format_str + num;
		}

		
		var MainEvent = {

		}

		
		var MainTableModel = function(data,parent){
			var self = this;
			self.model = modelInit(data);

			function modelInit(data){
				var count = 1;
				var data = _.map(data, function(item){

					var items = {};

					_.forOwn(item, function(val,key){
						items[key] = ko.observable(val);
					});
					
					items.click = function(e){
						//console.log(e);
					}


					items.row_num = count;
					count++;
					return items;
				});
				return ko.observableArray(data);
			}

		}

		
		var TeacherView = function(data, parent){
			var self = this;
			self.model = ko.observableArray();
			self.select = ko.observableArray(data.select);
			self.selectValue = ko.observable();
			self.name = ko.observable(data.name);
			self.teacher_id = data.id;

		
			self.state =ko.observable({
				expand:ko.observable(false)
			});
			self.changestate = function(){
				self.state().expand( !self.state().expand() );
				//console.log(self.state());
			}

			self.addcourse = function(){

					var submit_obj = {
						teacher_id : self.teacher_id,
						table_name : 'teacher',
						course_id : self.selectValue().course_id
					}

					var dataS = {
						table_method : "addcourse",
						table_data : submit_obj,
						table_name: 'teacher'
					}
					jQuery.ajax({
							type:'POST',
							url:ajaxurl + "?action=test_ajax",
							data:dataS	
						})
						.done(function(resp){
							//console.log(resp);
							window.location.reload();
					    });
					
			}
			self.delcourse = function( e ){
					var submit_obj = {
						teacher_id : e.teacher_id,
						table_name : 'teacher',
						course_id : e.course_id
					}

					var dataS = {
						table_method : "delcourse",
						table_data : submit_obj,
						table_name: 'teacher'
					}
					
					jQuery.ajax({
							type:'POST',
							url:ajaxurl + "?action=test_ajax",
							data:dataS	
						})
						.done(function(resp){
							//console.log(resp);
							window.location.reload();
					    });
					
			}

			var init = function(){
				var init_arr = _.map( data.data, function(it){
					it.del = self.delcourse;
					return it;
				});	
				self.model(init_arr);
			}
			init();
		}

		function ViewModel(){
			var self = this;
			
			self.dataP = ko.observable();


			self.dateBut = function(e){
				//console.log(self.alterDate() + '  ' + self.inpDate());
			}

			self.close_pay = function(e, e1){
						jQuery('#paymentDivModal').html('');
						jQuery('#paymentDivModalbg').hide();	
			}

			self.choiceDiv = {
				newUser:function(){
					$("#clientCourseViewUsers .exists").hide();
					$("#clientCourseViewUsers .new").show();
				},
				link:'',
				form:{
					client_name:ko.observable(''),
					client_fullname:ko.observable(''),
					client_email:ko.observable(''),
					role:ko.observable(''),
					client_password:ko.observable(''),
					client_password2:ko.observable('')
				},
				cancel:function(){
					$("#clientCourseViewUsers").hide();
				},
				clickReg:function(e){
					var submit_obj = {}
					_.forOwn(self.choiceDiv.form, function(val, key){
						submit_obj[key] = val();
					});
					var dataS = {
						table_method : "register",
						table_data : submit_obj,
						table_name: ''
					}
						jQuery.ajax({
							type:'POST',
							url:ajaxurl + "?action=test_ajax",
							data:dataS	
						})
						.done(function(resp){
							var tail = resp.slice(resp.length -2, resp.length );
							if(tail === "}0") {
								resp =  resp.slice(0,-1);
							};
							
							//console.log(resp);
							resp = JSON.parse(resp);
							var cid = resp.res.client_id;
							var dataS = self.choiceDiv.link;
							dataS.table_data.client_id =  cid ;
							//console.log(dataS);
							jQuery.ajax({
								type:'POST',
								url:ajaxurl + "?action=test_ajax",
								data:dataS	
							})
							.done(function(resp){
								window.location.reload();

								//console.log(resp);
							})
							.error(function(error){
								//console.log(error);
							});



					    })
					    .error(function(error){
								//console.log(error);
						});
					
				}
			}	

			self.clientSearchResults  = ko.observableArray();



			self.views = {};

			if(window.teacher_and_courses !== undefined){
				self.teacherView = ko.observableArray();
					_.each(teacher_and_courses, function(it){
						self.teacherView.push( new TeacherView(it, self) );
					});
				//console.log(self.teacherView());
			}

			if(window._DATAVIEWS !== undefined)	{		
				_.forOwn(_DATAVIEWS, function(data, key){
					self.views[key] = ko.observable( new ViewsTableModel(data,self, selects) );
				});
			}

			if(window.__data_main !== undefined)	{
			    	self.mainView = ko.observable( new MainTableModel(window.__data_main, self));	
			}

			self.searchString = ko.observable('');

			if(window.profile_courses !== undefined)	{		
				self.profile_courses = ko.observableArray(profile_courses);
			}	

			self.clickSearch = function(){
				
				var dataS = {
					table_name:"clientcourse",
					table_data:{
						"reset":0,
						"searchkey": self.searchString()
								},
					table_method:'search'			
				};
				//console.log(ajaxurl + "?action=test_ajax");
				jQuery.ajax({
					type:'POST',
					url:ajaxurl + "?action=test_ajax",
					data:dataS
						
				})
				.done(function(resp){
					
					var tail = resp.slice(resp.length -2, resp.length );
					if(tail === "]0") {
						resp =  resp.slice(0,-1);
					};
					resp = JSON.parse(resp);
					self.views.clientcourseView().enumerate(  resp );
				});

			};
			self.clickReset = function(){
				
				var dataS = {
					table_name:"clientcourse",
					table_data:{
						"reset":1
								},
					table_method:'search'			
				};
				//console.log(ajaxurl + "?action=test_ajax");
				$.ajax({
					type:'POST',
					url:ajaxurl + "?action=test_ajax",
					data:dataS
						
				})
				.done(function(resp){
					var pos = resp.indexOf('[{');
					resp = resp.slice(pos);
					var tail = resp.slice(resp.length -2, resp.length );
					if(tail === "]0") {
						resp =  resp.slice(0,-1);
					}
					resp = JSON.parse(resp);
					self.views.clientcourseView().enumerate(  resp );
					self.searchString('');
				});

			}

			self.testajax = function(){

				var dataS = {
					table_name:"user",
					table_data:{"iduser":"3",
								"wp_user_id":"1",
								"role_id":"3"},
					table_method:'insert'			
				};
				//console.log(ajaxurl + "?action=test_ajax");
				$.ajax({
					type:'POST',
					url:ajaxurl + "?action=test_ajax",
					data:dataS	
				})
				.done(function(resp){
					//console.log(resp);
				});
			}

			//console.log(self.views);

			self.edit_record = function(e){
				//console.log(e);
			}
		}

		jQuery(function(){
			ko.bindingHandlers.squareTable = 	{
				init: function(element, valueAccessor) {
					var value = valueAccessor();
					if(value !== undefined){

						if( value.count()==='' ) value.count(0);

				        jQuery(element).addClass("squareTable");
				        for (var i = 1; i <= value.total(); i++){
				           var $d = jQuery("<div>");
				           $d.text(i);
				       	   $d.appendTo(element);

				       	   if( i % 4 === 0 ){
				       	   		jQuery('<br>').appendTo(element);
				       	   }

				       	 }  
				       jQuery('div',element).each(function(index){
				       		jQuery(this).toggleClass("choosen", index < value.count());		       				       	
				       		jQuery(this).hover(
				       			function(){ 
				       				if(value.edit !== undefined){
					       				if(value.edit()){
						       				jQuery(this).prevAll().addClass("hoverChoosen"); 
						       				jQuery(this).addClass("hoverChoosen");
						       			}
					       			}
				       			},
				       			function(){ 
				       				if(value.edit !== undefined){
					       				if(value.edit()){
						       				jQuery(this).prevAll().removeClass("hoverChoosen");
						       				jQuery(this).removeClass("hoverChoosen");
						       			}
					       			}
				       			}
				       		).click(function(){
				       			if(value.edit !== undefined){
					       			if(value.edit()){
					       				var count = value.count()-1;
					       				if(count >= index){
					       					value.count(index);
					       				}else{
					       					value.count(index+1);
					       				}
									}
								}
				       		})
				       });
				    }
			    },

			    update:function(element,valueAccessor){
			    	var value = valueAccessor();
			    	jQuery("div",element).each(function(index){
			    		jQuery(this).toggleClass("choosen", index < value.count());		       				       	
			    	});
			    }
				
			};

			
			ko.bindingHandlers.datepicker = {
			    init: function(element, valueAccessor, allBindingsAccessor) {
			    	var options = allBindingsAccessor().datepickerOptions || {
						format:"dd-mm-yyyy",
				   		monthsFull: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
						weekdaysShort: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб' ],
						today: 'Сегодня',
						clear: 'Очистить',
						close: 'Закрыть',
						formatSubmit: 'dd-mm-yyyy'		        	
			        },
			        $el = jQuery(element);
			        
			        $val = valueAccessor();


			        $el.pickadate(options);
			        $el.pickadate('select', $val);
			        $el.bind('change', function(){
			        	var observable = valueAccessor();
			            observable($el.val());
			        });
			    }

			}

		   ko.applyBindings(new ViewModel());

		   var pop = {
		   		format:"dd-mm-yyyy",
		   		monthsFull: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
				weekdaysShort: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб' ],
				today: 'Сегодня',
				clear: 'Очистить',
				close: 'Закрыть',
				formatSubmit: 'dd-mm-yyyy'
		   }
		  jQuery('.pickadate').pickadate(pop);
			
		});
	</script>

	<?php  } ?>